/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Apr 13, 2012  12:44:40 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.sd.outbound
 * File Name : VwSyncMktBankDeduRequService.java
 * TODO
 */
package sap.business.sd.outbound;

import java.util.ArrayList;
import java.util.List;
import jpa.entitys.synchro.staging.SdCustoRequDeducOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.SdCustoRequDeducOutbServices;
import org.apache.log4j.Logger;
import promis.utility.CommonService;
import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoStructure;
import com.sap.conn.jco.JCoTable;

/**
 * @author chatree
 *
 */
public class VwSyncMktBankDeduRequService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(VwSyncMktBankDeduRequService.class);
	private SdCustoRequDeducOutbServices SdCustoRequDeducOutbServ;
	private String sap_table_bank;
	private String sap_table_card;

	/**
	 * 
	 */
	public VwSyncMktBankDeduRequService() {
		// TODO Auto-generated constructor stub
		try {
			
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
			
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	private JCoTable Bank(JCoFunction jcoFunction, List<?> value_list) throws Exception {
		JCoTable jcoTable_bank = jco_conn.getTables(this.sap_table_bank);
		try{
			
			if(!jcoTable_bank.isEmpty())
			{
				log.info("Bapi = "+ sap_bapi +", table : "+ sap_table_bank +" is not Empty ");
				return null;
			}
			
			jcoTable_bank.deleteAllRows();
			if(!CommonService.IsNull(value_list)){
				log.info("value_list.size : " + value_list.size());			
				log.info("table.getNumRows : " + jcoTable_bank.getNumRows());				
				
				for (Object obj : value_list) 
		        {
					SdCustoRequDeducOutb model = (SdCustoRequDeducOutb)obj;
					if(CommonService.IsNullRString(model.getCusRequType()).equals("REQUEST_BANK"))
					{
						
						log.info(" -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + "  InstanceNo = " + model.getInstanceNo() + " getDocumentNo = " + model.getDocumentNo());
						
						jcoTable_bank.appendRow();
						jcoTable_bank.setValue("PROMIS_TXN_ID", model.getPromisStagingId());						
						
						jcoTable_bank.setValue("BANK_COUNTRY", model.getBankCountry());
						jcoTable_bank.setValue("BANK_KEY", model.getBankKey());
						jcoTable_bank.setValue("BANK_ACCOUNT", model.getBankAccountNo());
						jcoTable_bank.setValue("ACCT_HOLDER", model.getBankAccountName());
						//jcoTable_bank.setValue("BANK_ACOUNT_TYP", model.getBankAcType());
						jcoTable_bank.setValue("BANK_ACOUNT_TYP", "");
						jcoTable_bank.setValue("REF_DETAIL", model.getBankRemarks());
						jcoTable_bank.setValue("BANK_PERIOD", model.getBankDeductPeriod());
						jcoTable_bank.setValue("BANK_START", model.getBankStartPay());
						jcoTable_bank.setValue("BANK_END", model.getBankEndPay());
						jcoTable_bank.setValue("BANK_AMOUNT", model.getBankDeductAmount());
						jcoTable_bank.setValue("BANK_PAID_DATE", model.getBankDateForDeduct());
					}
		        }
			}			
			
		}catch(Exception e)
		{
			log.error(e);
			throw e;
		}	
		
		return jcoTable_bank;
	}
	
	private JCoTable Card(JCoFunction jcoFunction, List<?> value_list) throws Exception {
		
		JCoTable jcoTableCard = jco_conn.getTables(this.sap_table_card);
		try{
						
			if(!jcoTableCard.isEmpty())
			{
				log.info("Bapi = "+ sap_bapi +", table : "+ sap_table_card +" is not Empty ");
				return null;
			}	
			
			if(!CommonService.IsNull(value_list)){
				log.info("value_list.size : " + value_list.size());			
				log.info("table.getNumRows : " + jcoTableCard.getNumRows());
				
				jcoTableCard.deleteAllRows();
				for (Object obj : value_list) 
		        {
					SdCustoRequDeducOutb model = (SdCustoRequDeducOutb)obj;
					if(CommonService.IsNullRString(model.getCusRequType()).equals("REQUEST_CARD"))
					{
						log.info(" -- PROMIS_TXN_ID = " +  model.getPromisStagingId() + "  InstanceNo = " + model.getInstanceNo() + " getDocumentNo = " + model.getDocumentNo());
						
						jcoTableCard.appendRow();
						jcoTableCard.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
						
						jcoTableCard.setValue("PAY_CARD_TYP", model.getCardType());
						jcoTableCard.setValue("BANK_KEY", model.getCardBankCode());
						jcoTableCard.setValue("CARD_NO", model.getCardCreditCardNo());
						jcoTableCard.setValue("CARD_VALID_FR", model.getCardValidFrom());
						jcoTableCard.setValue("CARD_VALID_TO", model.getCardValidTo());
						jcoTableCard.setValue("CARD_HOLDER", model.getCardCreditCardName());
						jcoTableCard.setValue("CARD_PERIOD", model.getCardDeductPeriod());
						jcoTableCard.setValue("CARD_START", model.getCardStartPay());
						jcoTableCard.setValue("CARD_END", model.getCardEndPay());
						jcoTableCard.setValue("CARD_AMOUNT", model.getCardDeductAmount());
						jcoTableCard.setValue("CARD_PAID_DATE", model.getCardDateForDeduct());
					}
		        }
			}
		}catch(Exception e)
		{
			log.error(e);
			throw e;
		}
		
		return jcoTableCard;
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoStructure jCoStructure, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		
		if(CommonService.IsNull(value_list))
		{
			log.info("Bapi = "+ sap_bapi +", sap_table_card : "+ sap_table_card +",  sap_table_bank : "+ sap_table_bank +" , structure : "+ sap_structure +" is not Empty ");
			return;
		}

		try{
			
			if(!CommonService.IsNull(value_list))
			{
				log.info("value_list size : " + value_list.size());
				
				SdCustoRequDeducOutb value = (SdCustoRequDeducOutb)value_list.get(0);
				
				jCoStructure.clear();
				jCoStructure.setValue("INTERFACE_NO", "SDI06");
				jCoStructure.setValue("PROMIS_DOCNO", value.getContractNo());				
				jCoStructure.setValue("PROMIS_CUSNO", "");
				jCoStructure.setValue("STATUS", value.getStatus());
				
				JCoTable jcoTable_bank = Bank(jcoFunction, value_list);
								
				JCoTable jcoTable_card = Card(jcoFunction, value_list);
			}
			
			super.SynchroToSap(jcoFunction, jCoStructure, value_list);
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		
		List<SdCustoRequDeducOutb> lst = new ArrayList<SdCustoRequDeducOutb>();				
		if(jcoTable_return != null && jcoTable_return.isEmpty() == false)
		{
			log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
			for(int i = 0; i < jcoTable_return.getNumRows(); i++)
			{
				jcoTable_return.setRow(i);			
				SdCustoRequDeducOutb model = SdCustoRequDeducOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
				log.info(CommonJCOReturn.toString(jcoTable_return));
				
				if(model != null){
					model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
					model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
					model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
					model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
					model.setIsactive("Y");
					model.setIssync("Y");
					
					lst.add(model);
				}
			}
			
			if(!CommonService.IsNull(lst)){
				
				SdCustoRequDeducOutbServ.Updated(lst);
				log.info(" Update Staging CallbackMessageFromSap size : " + lst.size());
				
			}
		}else
			log.info(CommonJCOReturn.toString(jcoTable_return));
		
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	
	private void UpdateStagingWhenError(List<SdCustoRequDeducOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<SdCustoRequDeducOutb> newlst = new ArrayList<SdCustoRequDeducOutb>();
				for(SdCustoRequDeducOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new SdCustoRequDeducOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendingToSAP(List<SdCustoRequDeducOutb> value_list) throws Exception 
	{
		log.info("SendingToSAP Start ==================> ");
		try{			
			if(!CommonService.IsNull(value_list))
			{
				
				this.sap_bapi = "ZIN_SD_CUSTPAYMENT_PROCESSING";			
				this.sap_structure = "HEADER";
				this.sap_table = "";
				this.sap_table_bank = "BANK_ACCT";
				this.sap_table_card = "PAYMENT_CARD";			
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
				
				SdCustoRequDeducOutbServ = new SdCustoRequDeducOutbServices(this.emSynchro);

				//Get SAP BAPI function
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table Header
				//JCoTable jcoTable = jco_conn.getTables(sap_table);
				JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
						
				//List<SdCustoRequDeducOutb> value_list = SdCustoRequDeducOutbServ.findAllIsSync("N");
				
				SynchroToSap(jcoFunction, jCoStructure, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}
		}catch(Exception e)
		{
			UpdateStagingWhenError(value_list, e);
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}

	@Deprecated
	private void Start() throws Exception
	{
		try{
			
			this.sap_bapi = "ZIN_SD_CUSTPAYMENT_PROCESSING";			
			this.sap_structure = "HEADER";
			this.sap_table = "";
			this.sap_table_bank = "BANK_ACCT";
			this.sap_table_card = "PAYMENT_CARD";			
			this.sap_table_return = "RETURN";
			this.jco_conn  = new Connection();
			
			SdCustoRequDeducOutbServ = new SdCustoRequDeducOutbServices(this.emSynchro);

			//Get SAP BAPI function
			JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
			
			//Get SAP Staging table Header
			//JCoTable jcoTable = jco_conn.getTables(sap_table);
			JCoStructure jCoStructure = jco_conn.getImportStructure(sap_structure);
					
			List<SdCustoRequDeducOutb> value_list = SdCustoRequDeducOutbServ.findAllIsSync("N");
			
			SynchroToSap(jcoFunction, jCoStructure, value_list);
			
			//Get SAP Staging table retrun message
			JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
			CallbackMessageFromSap(jcoTable_return);
			
		}catch(Exception e)
		{
			log.error(e.getMessage());
			System.err.println(e.getMessage());
			throw e;
		}
	}
	
	
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			
//			VwSyncMktBankDeduRequService obj = new VwSyncMktBankDeduRequService();
//			
//			obj.Start();
//			
//		}catch(Exception ex)
//		{
//			log.error(ex);
//		}
//
//	}

}
